#!/usr/bin/php5
<?PHP

function drawpixel($screen, $x, $y, $color)
{
    $rect = array(
        'x' => $x,
        'y' => $y,
        'w' => 1,
        'h' => 1
    );

    SDL_FillRect($screen, $rect, SDL_MapRGB($screen['format'], $color[0], $color[1], $color[2]));
}

function drawVline($screen, $x, $y, $len, $color)
{
    $rect = array(
        'x' => $x,
        'y' => $y,
        'w' => 1,
        'h' => $len
    );

    SDL_FillRect($screen, $rect, SDL_MapRGB($screen['format'], $color[0], $color[1], $color[2]));
}

function drawRect($screen, $x, $y, $w, $h, $color)
{
    $rect = array(
        'x' => $x,
        'y' => $y,
        'w' => $w,
        'h' => $h
    );

    SDL_FillRect($screen, $rect, SDL_MapRGB($screen['format'], $color[0], $color[1], $color[2]));
}

function drawBox($screen, $x, $y, $w, $h, $border, $border_color, $color)
{
    drawRect($screen, $x, $y, $w, $h, $border_color);
    drawRect($screen, $x + $border, $y + $border,
            $w - 2 * $border, $h - 2 * $border, $colo);
}

function drawCircle($srceen, $x, $y, $r, $color)
{
    $sx = $x - $r;
    $sy = $y - $r;
    $ex = $x + $r;
    $ey = $y + $r;

    for ($i = $sy; $i < $ey; ++$i) {
        for ($j = $sx; $j < $ex; ++$j) {
            if (($i - $y) * ($i - $y) + ($j - $x) * ($j - $x) <= $r * $r)
                drawpixel($srceen, $j, $i, $color);
        }
    }
}

function main()
{
    if (!extension_loaded("sdl")) {
       if (!dl("sdl.so"))
           die("sdl扩展加载失败!\n");
    }

    SDL_Init(SDL_INIT_VIDEO);

    $screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);

    // drawpixel($screen, 100, 100, [255, 0, 0]);
    // drawVline($screen, 100, 100, 100, [255, 0, 0]);

    // drawBox($screen, 100, 100, 200, 200, 10, [255, 0, 0], [0, 0, 0]);

    drawCircle($screen, 100, 100, 50, [255, 0, 0]);

    SDL_Flip($screen);

    while (TRUE)
    {
        if (SDL_WaitEvent($event))
        {
            if ($event['type'] == SDL_QUIT)
                break;
            else if ($event['type'] == SDL_KEYDOWN)
            {
                if ($event['key']['keysym']['sym'] == 27)
                    break;
            }
            else if ($event['type'] == SDL_MOUSEBUTTONDOWN)
            {
                if ($event['button']['button'] == SDL_BUTTON_LEFT)
                printf("x = %d, y = %d\n", $event['button']['x'], $event['button']['y']);
            }
        }
    }

    SDL_Quit();

    return 0;
}

exit(main());

